// 和用户相关状态管理

import {createSlice} from '@reduxjs/toolkit'
import {setToken as settoken, getToken, removeToken} from '@/utils'
import {getLogin, getUserInfo} from '@/api/user'




const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        // token令牌
        token: getToken() || '',
        userInfo: {}
    },
    // 同步修改
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            // 本地存储一份
            settoken(action.payload)
        },
        setUserInfo(state ,action) {
            state.userInfo = action.payload
        },
        // 清理用户信息
        clearUserInfo(state) {
            state.userInfo = {}
            state.token = ''
            removeToken()
            
        }
    }
})

// 异步请求数据
// 登录获取token
const fetchLogin = (loginForm) => {
    return  async (dispatch) => {
        //1. 发送异步请求
        const res =  await getLogin(loginForm)
        dispatch(setToken(res.data.token))
        console.log(res.data.token);
    }
}
// 获取用户信息
const fetchUserInfo =  () => {
    return  async (dispatch) => {
        const res =  await getUserInfo()
        dispatch(setUserInfo(res.data))
        console.log(res.data);
    }
}







//解构
const {setToken, setUserInfo,  clearUserInfo } = userStore.actions

const reducer = userStore.reducer

export {setToken, fetchLogin, setUserInfo, fetchUserInfo,  clearUserInfo }

export default reducer